﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Linq.Expressions;

namespace MvcEngine.Core.Registry
{
    public class ControllerActionCriteria : IFilterCriteria
    {
        private readonly List<ReflectedActionDescriptor> actions = new List<ReflectedActionDescriptor>();

        public void AddAction<T>(Expression<Func<T, object>> method)
        {
            MethodCallExpression methodCall = method.Body as MethodCallExpression;

            if (methodCall == null)
                throw new InvalidOperationException();

            actions.Add(new ReflectedActionDescriptor(methodCall.Method, methodCall.Method.Name, new ReflectedControllerDescriptor(methodCall.Object.Type)));
        }

        public bool Match(ActionFilterRegistryContext context)
        {
            ReflectedActionDescriptor reflectedDescriptor = context.ActionDescriptor as ReflectedActionDescriptor;
            if (reflectedDescriptor != null)
                return actions.Any(a => a.MethodInfo == reflectedDescriptor.MethodInfo);

            return actions.Any(a => a.ControllerDescriptor.FindAction(context.ControllerContext, context.ActionDescriptor.ActionName) != null);
        }
    }
}
